package com.puhui.lib.base.mvp

import android.app.Activity
import androidx.annotation.StringRes
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import com.blankj.utilcode.util.ActivityUtils
import com.puhui.lib.base.MvpBaseActivity
import com.puhui.lib.base.MvpBaseFragment
import com.puhui.lib.http.retrofit.BaseServiceApi
import com.puhui.lib.network.NetworkManager
import com.puhui.lib.network.callback.NetworkCallBack
import com.puhui.lib.utils.ToastUtil
import io.reactivex.Observable
import org.greenrobot.eventbus.EventBus

open class RootPresenter<V : IView> constructor(private val mView: V) : IPresenter {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    override fun onStart() {
        if (needEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    override fun onDestroy() {

        if (needEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    fun <T : BaseServiceApi> getApiService(apiService: Class<T>): T {
        return NetworkManager.getApiService(apiService)
    }

    fun <T> doSubscribe(source: Observable<T>, callBack: NetworkCallBack<T>?) {
        NetworkManager.doSubscribe(source, callBack)
    }

    fun getActivity(): Activity {
        val context = mView.getTopContext()
        if (context is Activity) return context

        return ActivityUtils.getTopActivity()
    }

    fun startLoading() {
        if (mView is MvpBaseActivity<*, *>) {
            mView.startLoading()
        } else if (mView is MvpBaseFragment<*, *>) {
            mView.startLoading()
        }
    }

    fun stopLoading() {
        if (mView is MvpBaseActivity<*, *>) {
            mView.stopLoading()
        } else if (mView is MvpBaseFragment<*, *>) {
            mView.stopLoading()
        }
    }

    fun getString(@StringRes strRes: Int): String {
        return mView.getResString(strRes)
    }

    fun showToast(toastMsg: String) {
        ToastUtil.showToast(toastMsg)
    }
}